package com.guigu.springcloud.controller;

import com.guigu.springcloud.common.CommonResult;
import com.guigu.springcloud.entity.Payment;
import com.guigu.springcloud.service.PaymentService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping
    public CommonResult create(@RequestBody Payment payment) {
        log.info(payment.toString());
        int result = paymentService.create(payment);
        return CommonResult.voData(200, "创建成功"+serverPort, result);
    }

    @GetMapping(value = "/{id}")
    public CommonResult findById(@PathVariable("id") Long id) {
        log.info(id.toString());
        Payment payment = paymentService.findById(id);
        log.info(payment.toString());
        return CommonResult.voData(200, "查询成功"+serverPort, payment);
    }

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service: services) {
            log.info("****服务名***"+service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance: instances) {
                log.info("--该服务信息---"+instance.getInstanceId()+"\t"+instance.getHost()+"\t"+
                        instance.getPort()+"\t"+instance.getUri());

            }
        }
        return discoveryClient;
    }

    @GetMapping("/myloadBalance")
    public String getServicePort(){
        return serverPort;
    }
}
